package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.ChangeListAdapter;
import com.jsnj33.pdaproject.adapter.FormAdapter;
import com.jsnj33.pdaproject.adapter.FormHorizontalAdapter;
import com.jsnj33.pdaproject.base.BaseActivity;
import com.jsnj33.pdaproject.bean.BatchAndProductBean;
import com.jsnj33.pdaproject.bean.ChangeBean;
import com.jsnj33.pdaproject.bean.FormGoodsBean;
import com.jsnj33.pdaproject.bean.MainBean;
import com.jsnj33.pdaproject.bean.MsgBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.SaNetUtils;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.StringEntity;

public class GZ_ChangeListActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "FormActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    private Button btnRetryScan;
    private TextView title;
    private TextView tvOrder;
    private RelativeLayout rProgressBar;
    private TextView tv_gh_no;
    private TextView tv_order;

    private AlertDialog dialog;
    private ChangeListAdapter adapter;
    private List<MainBean> listAdress;
    private String tailUrl;
    private String oldTailUrl;
    private String os_no = "";
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            String str = new String(barcode, 0, barcodelen);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(GZ_ChangeListActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);
            switch (sbs) {
                case "ht":
                    tv_order.setText(sbs);
                    scanningProductName(str);
                    break;
                default:
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_gz_form);
        btnRetryScan = findViewById(R.id.btnRetryScan);
        tv_order = findViewById(R.id.tv_order);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();

        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    private void initData() {
        title = findViewById(R.id.title);
        tv_gh_no = findViewById(R.id.tv_gh_no);
        rProgressBar = findViewById(R.id.rProgressBar);
        RecyclerView rvHorizontal = findViewById(R.id.recyclerview_horizontal);
        RecyclerView rvVertical = (RecyclerView) findViewById(R.id.recyclerview_vertical);
        tvOrder = (TextView) findViewById(R.id.tv_order);
        Button submit = (Button) findViewById(R.id.submit);

        tvOrder.setOnClickListener(this);
        submit.setOnClickListener(this);

        Intent intent = getIntent();
        if (intent != null) {
            title.setText(getIntent().getStringExtra("title"));
            listAdress = (List<MainBean>) getIntent().getSerializableExtra("list");
            tailUrl = listAdress.get(0).getAddress();
            oldTailUrl = tailUrl;
        }
        rvHorizontal.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvHorizontal.setNestedScrollingEnabled(false);//禁止滑动
        FormHorizontalAdapter adapterHorizontal = new FormHorizontalAdapter(this) {
            @Override
            protected void itemChick(String address) {
                tailUrl = address;
            }
        };
        rvHorizontal.setAdapter(adapterHorizontal);
        adapterHorizontal.setList(listAdress);


        initRecyclerView(rvVertical, LinearLayoutManager.VERTICAL);
        btnRetryScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeInfo();
            }
        });
    }

    private void initRecyclerView(RecyclerView recyclerView, int vertical) {
        recyclerView.setLayoutManager(new LinearLayoutManager(this, vertical, false));
        recyclerView.setNestedScrollingEnabled(false);//禁止滑动
        adapter = new ChangeListAdapter(this);
        recyclerView.setAdapter(adapter);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void scanningProductName(final String barcode) {
        boolean b = judgeString(barcode);
        if (b == true) {
            ToastUtil.showGravityToast(GZ_ChangeListActivity.this, "二维码不存在！！！", Gravity.CENTER, 0, 0);
            return;
        }
        RequestParams requestParams = new RequestParams(Constants.CHANGELIST);
        final JSONObject map = new JSONObject();
        try {
            map.put("barcode", barcode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        requestParams.setBodyContent(map.toString());
        requestParams.setAsJsonContent(true);
        Log.d(TAG, "scanningProductName: URL:" + requestParams.getUri());
        Log.d(TAG, "scanningProductName: Params:" + map.toString());
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                Log.d(TAG, "onSuccess: " + result.toString());
                String respCode = result.optString("respCode");
                if (respCode.equals("1")) {
                    ArrayList<ChangeBean> list = new Gson().fromJson(result.optString("respData"), new TypeToken<ArrayList<ChangeBean>>() {
                    }.getType());
                    adapter.setList(list);
                } else {
                    ToastUtil.showToast(GZ_ChangeListActivity.this, "" + result.optString("respMsg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "Throwable: " + ex.getMessage());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 提交数据后清空数据
     */
    private void removeInfo() {
        clearText(tvOrder);
        adapter.setList(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeInfo();
    }

    private void clearText(TextView... textViews) {
        for (int i = 0; i < textViews.length; i++) {
            textViews[i].setText("");
        }
    }

    /**
     * 判断必传参数中是否有null或者""。
     *
     * @param str
     * @return true:有  false:无
     */
    private boolean judgeString(String... str) {
        for (int i = 0; i < str.length; i++) {
            if (StringUtility.isEmpty(str[i])) {
                return true;
            }
        }
        return false;
    }
}
